// ~ CopyRight © 2012 USTC SINOVATE  SOFTWARE CO.LTD All Rights Reserved.
package com.cmcc.zysoft.spring.security.filter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.GenericFilterBean;

import com.cmcc.zysoft.infocollection.mobile.util.FileUploadUtil;

/**
 * @author 闫豆
 * @mail yan.dou@ustcinfo.com
 * @date 2013-1-22 下午9:26:00
 */
public class MobileUploadFilter extends GenericFilterBean {
	
	@Value("${upload.mobile.img.path}")
	private String uploadPath;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		int readSize = this.upload(request, response);
		request.setAttribute("readSize", readSize);
		chain.doFilter(request, response);
	}
	
	/**
	 * @param request
	 * @param response
	 * @return 
	 * 返回类型：int
	 * @throws IOException 
	 */
	@SuppressWarnings("resource")
	private int upload(ServletRequest request, ServletResponse response) throws IOException{
		InputStream is = request.getInputStream();
		OutputStream os = null;
		
		int readSize = 0;
		HttpServletRequest req = (HttpServletRequest)request;
		//String uploadPath = req.getSession().getServletContext().getRealPath("/")+ "/uploadfiles/";
		
		String fileLocalName = req.getParameter("fileLocalName");
		String localNamePath = uploadPath + File.separator + fileLocalName;
		localNamePath = FileUploadUtil.replaceSeparator(localNamePath);
		os = new FileOutputStream(localNamePath, true);
		int byteread = 0;
		byte[] buffer = new byte[1];
		while ((byteread = is.read(buffer, 0, 1)) != -1) {
			readSize += byteread;
			os.write(buffer, 0, 1);
			os.flush();
		}
		return readSize;
	}

}
